<template>
  <div>
    <a-card>
      <div ref="lineChart1" :style="{width:'100%',height:'368px'}" ></div>
    </a-card>
  </div>
</template>
<script>

import { getAction } from '@/api/manage'
export default
{
  name: 'bmi',
  data() {
    return {
      url: {
        list: 'health/skBmiRecord/queryClassBmi',
        stuList: 'health/skBmiRecord/queryStudentBmiByMonth'
      },
      searchData: {
        semesterId: '',
        classId: '',
        studentId: ''
      },
      color:["#0CDF8A","#3EACE5"],
      numList:[]
    }
  },
  props:["dataForm","semesterName","className"],
  components: {},
  filters: {},
  
  computed: {},
  
  created() {
  },
  
  activated() {
  },

  mounted() {
    this.load()
  },

  methods: {
    load() {
      const dataForm = this.dataForm
      console.log(this.dataForm);
      this.numList = []
      // 查询列表数据
      this.searchData.semesterId = dataForm.semesterId ? dataForm.semesterId : dataForm.semesterHistoryId
      this.searchData.classId = dataForm.classId ? dataForm.classId : undefined
      this.searchData.studentId = dataForm.studentId ? dataForm.studentId : undefined
      if(dataForm.studentId) {
        this.studentChart()
      }else if(dataForm.classId) {
        this.classChart();
      }else{
        this.allChart()
      }
    },
    allChart() {
      // 查询运动数据
      const params = {
        statisticalScope: 'sex',
        semesterId: this.searchData.semesterId
      }
      getAction(this.url.list, params).then(res => {
        if(res.success) {
          // 各班平均
          var categorys = [];
          var xData1 = [[],[]];//男生
          var xData2 = [[],[]];//女生
          const classList = this.dataForm.classList.filter(item => { return item.id != ''});
          classList.forEach(el => {
            categorys.push(el.className);

            const nan = res.result.find(item => item.classId == el.id && item.sex == '1');//男生
            const nv = res.result.find(item => item.classId == el.id && item.sex == '2');//女生
            if (nan){
              xData1[0].push((nan.avgHeight).toFixed(2));
              xData1[1].push((nan.avgWeight).toFixed(2));
            } else {
              xData1[0].push(0);
              xData1[1].push(0);
            }
            if (nv){
              xData2[0].push((nv.avgHeight).toFixed(2));
              xData2[1].push((nv.avgWeight).toFixed(2));
            } else {
              xData2[0].push(0);
              xData2[1].push(0);
            }
          });
          this.initDoubleBarChart(this.$refs.lineChart1, '月平均身高体重统计', categorys, xData1, xData2);
        } else {
          this.$message.warning(res.message);
          this.loading = false;
        }
      })
    },
    classChart() {
       // 查询运动数据
       const params = {
        statisticalScope: 'student',
        semesterId: this.searchData.semesterId,
        classId: this.searchData.classId
      }
      getAction(this.url.list, params).then(res => {
        if(res.success) {
          // 各班平均
          var categorys = [];
          var xData1 = [];//身高
          var xData2 = [];//体重
          res.result.forEach(el => {
            categorys.push(el.studentName);
            xData1.push(el.height || 0);
            xData2.push(el.weight || 0);
          })
          this.initLineChart(this.$refs.lineChart1, '幼儿身高体重统计', categorys, xData1, xData2);
        } else {
          this.$message.warning(res.message);
          this.loading = false;
        }
      })
    },
    studentChart() {
      let params = {
        semesterId: this.searchData.semesterId,
        studentId: this.searchData.studentId,
      }
      getAction(this.url.stuList, params).then((res)=>{
        if(res.success){
          var categorys = [];
          var xData1 = [];//身高
          var xData2 = [];//体重

          // 每月
          const monthColumns = this.dataForm.monthColumns;
          console.log(monthColumns);
          for(let rowIndex = 0; rowIndex < monthColumns.length; rowIndex++){
            const rowString = monthColumns[rowIndex].toString();
            categorys.push(rowString);

            const monthData = res.result.find(item => item.month == rowString);
            if (monthData){
              xData1.push(monthData.height);
              xData2.push(monthData.weight);
            } else {
              xData1.push(0);
              xData2.push(0);
            }
          }
          this.initLineChart(this.$refs.lineChart1, '身高体重统计', categorys, xData1, xData2);
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    initDoubleBarChart(el, title, categorys, xData1, xData2) {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }
      myChartSports.clear() //清空画布数据

      var legendTitle = ['男生身高', '男生体重', '女生身高', '女生体重'];
      // option
      let optionSports = {
        backgroundColor: '#fff',
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.semesterName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          y: 'top', //延Y轴居中 
          x: 'right', //居右显示
          right: '20%'
        },
        grid: {
          left: '10%',
          top: '15%',
          right: '10%',
          bottom: '10%'
        },
        xAxis: {
          data: categorys,
          axisLine: {
            lineStyle: {
              color: '#666'
            }
          }
        },
        yAxis: [
          {
            name: legendTitle[0],
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
          {
            name: legendTitle[1],
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
        ],
        series: [
          {
            name: legendTitle[0],
            type: 'bar',
            barWidth: 10,
            yAxisIndex: 0,
            itemStyle: {
              normal: {
                barBorderRadius: [5,5,0,0],
                // color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                //   {
                //     offset: 0,
                //     color: '#0CDF8A'
                //   },
                //   {
                //     offset: 1,
                //     color: '#3EACE5'
                //   }
                // ]),
                color : '#3EACE5',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xData1[0]
          },
          {
            name: legendTitle[1],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                // barBorderRadius: 5,
                // color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                //   {
                //     offset: 0,
                //     color: '#0CDF8A'
                //   },
                //   {
                //     offset: 1,
                //     color: '#3EACE5'
                //   }
                // ]),
                color : '#92cc76',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xData1[1]
          },
          {
            name: legendTitle[2],
            type: 'bar',
            barWidth: 10,
            yAxisIndex: 0,
            itemStyle: {
              normal: {
                barBorderRadius: [5,5,0,0],
                // color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                //   {
                //     offset: 0,
                //     color: '#0CDF8A'
                //   },
                //   {
                //     offset: 1,
                //     color: '#3EACE5'
                //   }
                // ]),
                color : '#ee6666',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xData2[0]
          },
          {
            name: legendTitle[3],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            // barWidth: 10,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                // barBorderRadius: 5,
                // color: '',
                color : '#fac858',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xData2[1]
          },
        ]
      }

      myChartSports.setOption(optionSports);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    initLineChart(el, title, categorys, xData1, xData2) {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }
      myChartSports.clear() //清空画布数据

      var legendTitle = ['身高', '体重'];
      // option
      let optionSports = {
        backgroundColor: '#fff',
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.semesterName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          y: 'top', //延Y轴居中 
          x: 'right', //居右显示
          right: '20%'
        },
        grid: {
          left: '10%',
          top: '15%',
          right: '10%',
          bottom: '10%'
        },
        xAxis: {
          data: categorys,
          axisLine: {
            lineStyle: {
              color: '#666'
            }
          }
        },
        yAxis: [
          {
            name: legendTitle[0],
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
          {
            name: legendTitle[1],
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
        ],
        series: [
          {
            name: legendTitle[0],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            yAxisIndex: 0,
            itemStyle: {
              normal: {
                color : '#0BA6E3',
                label : {
                  position:'bottom',
                  show: true // 显示数据
                },
              }
            },
            data: xData1
          },
          {
            name: legendTitle[1],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                // barBorderRadius: 5,
                color: '#FFC005',
                label : {
                  position:'top',
                  show: true // 显示数据
                },
              }
            },
            data: xData2
          },
        ]
      }

      myChartSports.setOption(optionSports);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    handleEmit(){
      this.numList.push(true);
      if (this.numList.length == 1) {
        this.$emit("ok")
      }
    }
  }
}
</script>
<style scoped lang="less">
</style>